package org.lee.export.impl;

import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.xslf.usermodel.*;
import org.lee.export.IPptExporter;
import org.lee.export.model.PptVersion;
import org.lee.export.utils.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jackielee
 * @version 1.0
 * @description PptExporter 2007
 * @date 2021/5/6
 **/
public class PptExporterXSL extends BasicPptExporter implements IPptExporter {

    @Override
    public PptVersion getVersion() {
        return PptVersion.PPTX;
    }

    @Override
    protected List<String> doExport(File file, String pathSave) {
        List<String> pngFiles = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file)) {
            XMLSlideShow ppt = new XMLSlideShow(fis);
            Dimension pgsize = ppt.getPageSize();
            int idx = 1;
            for (XSLFSlide slide : ppt.getSlides()) {
                for (XSLFShape shape : slide.getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape textShape = (XSLFTextShape) shape;
                        for (XSLFTextParagraph p : textShape) {
                            for (XSLFTextRun r : p) {
                                r.setFontFamily("微软雅黑"); // 防止中文乱码
                            }
                        }
                    }
                }
                idx = exportPpt(file, pathSave, pngFiles, pgsize, idx, slide);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OfficeXmlFileException e) {
            e.printStackTrace(); // 2003,2007 ppt
        }
        return pngFiles;
    }

    private int exportPpt(File file, String pathSave, List<String> pngFiles, Dimension pgsize, int idx, XSLFSlide slide) throws IOException {
        String fileName = pathSave + File.separator + FileUtils.getFileName(file) + idx + ".png";
        File pngFile = new File(fileName);
        if (pngFile.exists()) {
            pngFile.delete();
        }
        System.out.println("exporting the pptx to png, page=" + idx);
        BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = img.createGraphics();
        // clear drawing
        g.setPaint(Color.white);
        g.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

        // render
        slide.draw(g);

        g.dispose();
        // save
        try (FileOutputStream fos = new FileOutputStream(pngFile)) {
            ImageIO.write(img, "png", fos);
            System.out.println("finish the pptx " + idx + " to png.");
            pngFiles.add(fileName);
            ++idx;
        }
        return idx;
    }
}
